<template>
  <div class='allocResource'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>分配资源</span>
      </div>
      <el-tree
        ref="rescource-tree"
        show-checkbox
        :data="rescource"
        :props="defaultProps"
        default-expand-all
        node-key="id"
        :default-checked-keys="checkedkeys"
      >
      </el-tree>
      <div class="bottom">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="resetChecked">清空</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang='ts'>
import Vue from 'vue'
import { Tree } from 'element-ui'
import { getRoleAll, getAll, getRoleResources, allocateRoleResources } from '@/services/rescource'
export default Vue.extend({
  name: 'allocResource',
  data () {
    return {
      rescource: [],
      defaultProps: {
        children: 'rescourceList',
        label: 'name'
      },
      checkedkeys: []
    }
  },
  created () {
    this.getAllRole()
    this.getRoleResources()
  },
  methods: {
    async getAllRole () {
      const { data } = await getRoleAll()
      const { data: allData } = await getAll()
      if (data.code === '000000' && allData.code === '000000') {
        this.rescource = data.data
        this.rescource.forEach((item: any) => {
          item.rescourceList = []
          allData.data.forEach((element: any) => {
            if (item.id === element.categoryId) {
              element.id = Math.random()
              item.rescourceList.push(element)
            }
          })
        })
      }
    },
    async getRoleResources () {
      if (this.$route.query.roleId) {
        const { data } = await getRoleResources((this.$route.query.roleId as string))
        if (data.code === '000000') {
          console.log(data.data)
          this.getCheckedKey(data.data)
        }
      }
    },
    getCheckedKey (rescource: any) {
      rescource.forEach((element: any) => {
        if (element.selected) {
          this.checkedkeys = [...this.checkedkeys, element.id] as any
        }
        // if (element.rescourceList) {
        //   this.getCheckedKey(element.rescourceList)
        // }
      })
    },
    async onSubmit () {
      const checkedNodes = (this.$refs['rescource-tree'] as Tree).getCheckedNodes()
      const resourceIdList: number[] = []
      checkedNodes.forEach(item => {
        console.log(item)
        if (!item.children) {
          resourceIdList.push(item.id)
        }
      })
      await allocateRoleResources({
        roleId: this.$route.query.roleId,
        resourceIdList
      })
      this.$message.success('保存成功')
      this.$router.back()
    },
    resetChecked () {
      (this.$refs['rescource-tree'] as Tree).setCheckedKeys([])
    }
  }
})
</script>
<style lang='scss' scoped>
.bottom {
  margin-top:20px ;
  display: flex;
  justify-content: center;
}
</style>
